#include "MemLinkRegistry.hpp"

bool MemLinkRegistry::registerHost(const HostInfo& host) {
    std::lock_guard<std::mutex> lock(registryMutex_);
    hostTable_[host.hostname] = host;
    return true;
}

std::vector<HostInfo> MemLinkRegistry::discoverHosts() {
    std::lock_guard<std::mutex> lock(registryMutex_);
    std::vector<HostInfo> result;
    for (const auto& [name, info] : hostTable_) {
        result.push_back(info);
    }
    return result;
}

int MemLinkRegistry::assignChannel(const std::string& hostname) {
    std::lock_guard<std::mutex> lock(registryMutex_);
    if (hostTable_.count(hostname) == 0) return -1;

    int channelId = nextChannelId_++;
    hostTable_[hostname].activeChannels.push_back(channelId);
    return channelId;
}

bool MemLinkRegistry::releaseChannel(const std::string& hostname, int channelId) {
    std::lock_guard<std::mutex> lock(registryMutex_);
    if (hostTable_.count(hostname) == 0) return false;

    auto& channels = hostTable_[hostname].activeChannels;
    channels.erase(std::remove(channels.begin(), channels.end(), channelId), channels.end());
    return true;
}

HostInfo MemLinkRegistry::getHost(const std::string& hostname) {
    std::lock_guard<std::mutex> lock(registryMutex_);
    return hostTable_[hostname];
}
